/**
 * Filename: OfficialListAdapter.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/3/6 16:23
 */
package com.github.postsanf.yinian.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.activity.ShopAddressEditActivity;
import com.github.postsanf.yinian.bean.YNAddress;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.utils.StringUtils;
import com.litesuits.http.HttpConfig;
import com.litesuits.http.LiteHttp;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;

import org.json.JSONObject;

import java.util.LinkedHashMap;
import java.util.List;

public class ShopAddressListAdapter extends RecyclerView.Adapter<ShopAddressListAdapter.ViewHolder> {
    public static final int TYPE_HEADER = 0;
    public static final int TYPE_NORMAL = 1;
    private Context context;
    private Activity activity;
    private List<YNAddress> datas;
    private View mHeaderView;
    private int userId;

    public ShopAddressListAdapter(Context context, List<YNAddress> datas, int userid) {
        this.context = context;
        this.activity = (Activity) context;
        this.datas = datas;
        this.userId = userId;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        LinearLayout order_address_next;
        TextView order_name;
        TextView order_telephone;
        TextView order_address;
        LinearLayout address_edit;
        LinearLayout address_delete;


        public ViewHolder(View itemView) {
            super(itemView);
            if (itemView == mHeaderView) return;
            order_address_next = (LinearLayout) itemView
                    .findViewById(R.id.order_address_next);
            order_name = (TextView) itemView
                    .findViewById(R.id.order_name);
            order_telephone = (TextView) itemView
                    .findViewById(R.id.order_telephone);
            order_address = (TextView) itemView
                    .findViewById(R.id.order_address);
            address_edit = (LinearLayout) itemView
                    .findViewById(R.id.address_edit);
            address_delete = (LinearLayout) itemView
                    .findViewById(R.id.address_delete);
        }

        public void bindData(final YNAddress listItems, final int point) {
            if (listItems != null) {
                order_name.setText(listItems.getAddressReceiver());
                order_telephone.setText(listItems.getAddressPhoneNumber());
                order_address.setText(listItems.getAddressDetail());
                address_edit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent mIntent = new Intent(context, ShopAddressEditActivity.class);
                        mIntent.putExtra("type", "modify");
                        mIntent.putExtra("YNAddress", listItems);
                        context.startActivity(mIntent);
                    }
                });
                address_delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        new AlertDialog.Builder(context).setMessage("确定删除该地址")
                                .setPositiveButton(R.string.yn_app_ok, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int whichButton) {
                                        EditAddressNext("delete", String.valueOf(listItems.getAddressID()), listItems.getAddressReceiver(),
                                                listItems.getAddressPhoneNumber(),
                                                listItems.getAddressProvince(), listItems.getAddressCity(), listItems.getAddressArea(),
                                                listItems.getAddressDetail(), point);
                                        context.sendBroadcast(new Intent(ACTIONs.actionUpdateShopAddress).putExtra("addressid", listItems.getAddressID()));

                                    }
                                }).setNegativeButton(R.string.yn_app_cancel, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                            }
                        }).show();
                    }
                });
                order_address_next.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(ACTIONs.actionUpdateShopReceiver);
                        intent.putExtra("YNAddress", listItems);
                        context.sendBroadcast(intent);
                        activity.finish();
                    }
                });
            }
        }
    }


    private void EditAddressNext(String type, String addressID, String receiver,
                                 String phone,
                                 String province,
                                 String city,
                                 String area,
                                 String detail, final int point) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put("userid", String.valueOf(userId));
        mParam.put("type", type);
        if (!StringUtils.isEmpty(addressID)) {
            mParam.put("addressID", addressID);
        }
        mParam.put("receiver", receiver);
        mParam.put("phone", phone);
        mParam.put("province", province);
        mParam.put("city", city);
        mParam.put("area", area);
        mParam.put("detail", detail);
        StringRequest req = new StringRequest(context.getString(R.string.SHOP_URL) + context.getString(R.string.ynManageAddress))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        try {
                            JSONObject jsonObject = new JSONObject(s.toString());
                            if (jsonObject.optString("msg").equals("success") && jsonObject.optInt("code") == 0) {
                                datas.remove(point);
                                notifyDataSetChanged();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        Toast.makeText(context, CommonConstants.YN_NET_LINK, Toast.LENGTH_SHORT).show();
                    }
                });
        LiteHttp.newApacheHttpClient(new HttpConfig(context)).executeAsync(req);
    }


    public void setHeaderView(View headerView) {
        mHeaderView = headerView;
        notifyItemInserted(0);
    }

    public View getHeaderView() {
        return mHeaderView;
    }

    @Override
    public int getItemViewType(int position) {
        if (mHeaderView == null) return TYPE_NORMAL;
        if (position == 0) return TYPE_HEADER;
        return TYPE_NORMAL;
    }

    private YNAddress getItem(int position) {
        return datas.get(position);
    }

    // 创建ViewHolder
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (mHeaderView != null && viewType == TYPE_HEADER) return new ViewHolder(mHeaderView);
        View convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.yn_item_address, parent, false);
        return new ViewHolder(convertView);
    }

    // 绑定数据到View
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        if (getItemViewType(position) == TYPE_HEADER) return;
        final int pos = getRealPosition(holder);
        YNAddress listItems = getItem(pos);

        holder.bindData(listItems, pos);
        holder.itemView.setTag(listItems);
    }

    public int getRealPosition(RecyclerView.ViewHolder holder) {
        int position = holder.getLayoutPosition();
        return mHeaderView == null ? position : position - 1;
    }


    @Override
    public int getItemCount() {
        return mHeaderView == null ? datas.size() : datas.size() + 1;
    }
}
